﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommonTools;
using CommonTools.Basic;
using shop.Model;

namespace shop.Bll.BasicInfo
{
    /// <summary> 辅助资料 </summary>
    public class JSubMessageBll : BasicBllParent, IFastQueryBll<JSubMessage>
    {

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="code">查询代码</param>
        /// <param name="isDetails">是否明细</param>
        /// <param name="msg">错误消息</param>
        /// <returns></returns>
        public override IEnumerable<object> Query(string code, bool isDetails, out string msg)
        {
            msg = null;
            var list = DB.FSql.Select<JSubMessage>()
                .Where(s => s.IsDetails == isDetails && s.Isdel == false);
            if (string.IsNullOrEmpty(code) == false)
            {
                list = list.Where(a => a.Code.StartsWith(code));
            }

            return list.ToList();      //排序

        }



        #region 分组: 增删改

        /// <summary> 添加分类 </summary>
        public override bool AddGroup(object obj, IUser user, out string msg)
        {
            msg = null;
            if (!(obj is JSubMessage model))
            {
                msg = Model.CN.Msg_InformationCannotBeBlank;  // "辅助资料为空";
                return false;
            }

            var id = DB.FSql.Insert(model).ExecuteIdentity();
            model.ID = (int)id;


            DB.FSql.Insert(new CLogs()
            {
                Computer = user.ComputerInfo,
                DocId = model.ID.ToString(),
                DocAction = "添加分类",
                DocName = nameof(JSubMessage),
                Note = $"代码:{model.Code},名称:{model.Name}",
            }).ExecuteAffrows();

             
            msg = CN.Msg_AddSuccess;  // "添加成功";
            return true;

        }

        /// <summary> 删除分类 </summary>
        public override bool DeleteGroup(object obj, IUser user, out string msg)
        {
            // 不能删除辅助资料分类
            msg = Model.CN.Msg_CannotDeleteSubMessageGroup;
            return false;

            //msg = null;
            //if (!(obj is JSubMessage model))
            //{
            //    msg = Model.CN.Msg_InformationCannotBeBlank;  // "辅助资料为空";
            //    return false;
            //}

            //if (dal.ClassChk(model))     //检查分类下是否由明细
            //{
            //    msg = CN.Msg_GroupHasItemsCannotDelete;  // "此分组下还有项目, 不能删除!";
            //    return false;
            //}

            //return dal.ClassDel(model, user, out msg);
        }

        /// <summary> 修改分组 </summary>
        public override bool UpdateGroup(object obj, IUser user, out string err)
        {
            err = "";
            if (!(obj is JSubMessage model))
            {
                err = Model.CN.Msg_InformationCannotBeBlank;  // "辅助资料为空";
                return false;
            }

            var item = DB.FSql.Select<JSubMessage>()
                .FirstOrDefault(a => a.Isdel == false && a.Code == model.Code);

            if (item != null)
            {
                item.Isdel = false;
                item.Name = model.Name;
                item.NameCn = model.NameCn;

                DB.FSql.ModifyFields(item, nameof(JSubMessage.Name), nameof(JSubMessage.NameCn));

                //日志
                DB.FSql.Insert(new CLogs()
                {
                    Computer = user.ComputerInfo,
                    DocId = item.ID.ToString(),
                    DocAction = "修改分类",
                    DocName = nameof(JSubMessage),
                    Note = $"代码:{item.Code},名称:{item.Name}",
                }).ExecuteAffrows();

                return true;
            }
            else
            {
                err = "错误, 没有找到此项目";
                return false;    //找不到内容, 可能已经被别人删除了
            }

        }

        #endregion

        

        #region 明细: 增删改


        /// <summary> 填加分类 </summary>
        public override bool Insert(object obj, IUser user, out string msg)
        {
            msg = null;
            if (!(obj is JSubMessage model))
            {
                msg = CN.Msg_SystemError;
                return false;
            }
            model.Isdel = false;
            model.IsDetails = true;

            if (string.IsNullOrEmpty(model.Code))
            {
                msg = CN.Msg_CodeCannotBeBlank;   // "资料代码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                msg = CN.Msg_NameCannotBeBlank;   // "资料名称不能为空";
                return false;
            }
            if (Query(model.Code,true, out var err2).Count()>0)
            {
                msg = CN.Msg_CodeCannotRepeat;    // "代码不能重复";
                return false;
            }


            model.Isdel = false;
            model.IsDetails = true;

            var id = DB.FSql.Insert(model).ExecuteIdentity();
            model.ID = (int)id;


            DB.FSql.Insert(new CLogs()
            {
                Computer = user.ComputerInfo,
                DocId = model.ID.ToString(),
                DocAction = "添加",
                DocName = nameof(JSubMessage),
                Note = $"代码:{model.Code},名称:{model.Name}",
            }).ExecuteAffrows();


            msg = null;
            return true;
        }


        /// <summary> 修改 </summary>
        public override bool Update(object obj, IUser user, out string msg)
        {
            msg = null;
            if (!(obj is JSubMessage model))
            {
                msg = CN.Msg_SystemError;
                return false;
            }
            if (model.ID <= 0)
            {
                msg = CN.Msg_IdCannotRepeat;   // "资料ID不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(model.Code))
            {
                msg = CN.Msg_CodeCannotBeBlank;   // "资料代码不能为空";
                return false;
            }
            if (string.IsNullOrEmpty(model.Name))
            {
                msg = CN.Msg_NameCannotBeBlank;   // "资料名称不能为空";
                return false;
            }

            if (DB.FSql.Select<JSubMessage>().Any(a=> a.Isdel== false && a.ID!=model.ID && a.Name== model.Name))
            {
                msg = "名称不能重复!";
                return false;
            }

            if (DB.FSql.Select<JSubMessage>().Any(a => a.Isdel == false && a.ID != model.ID && a.Code == model.Code))
            {
                msg = "代码不能重复!";
                return false;
            }

            DB.FSql.Update<JSubMessage>()
               .SetSource(model)
               .ExecuteAffrows();

            //日志
            DB.FSql.Insert(new CLogs()
            {
                Computer = user.ComputerInfo,
                DocId = model.ID.ToString(),
                DocAction = "修改",
                DocName = nameof(JSubMessage),
                Note = $"代码:{model.Code},名称:{model.Name}",
            }).ExecuteAffrows();

            msg = null;
            return true;

        }

        /// <summary> 删除 </summary>
        public override bool Delete(object obj, IUser user, out string msg)
        {
            msg = null;
            if (!(obj is JSubMessage model))
            {
                msg = CN.Msg_SystemError;
                return false;
            }
            if (model.ID <= 0)
            {
                msg = CN.Msg_IdCannotRepeat;   // "资料ID不能为空";
                return false;
            }

            model.Isdel = true;

            DB.FSql.ModifyFields(model, nameof(JSubMessage.Isdel));


            //日志
            DB.FSql.Insert(new CLogs()
            {
                Computer = user.ComputerInfo,
                DocId = model.ID.ToString(),
                DocAction = "删除",
                DocName = nameof(JSubMessage),
                Note = $"代码:{model.Code},名称:{model.Name}",
            }).ExecuteAffrows();

            msg = null;
            return true;

        }


        #endregion


        #region 实现IFastQueryBll 接口, 在FastBox中使用

        /// <summary> 在查询,报表中显式的标题名称 </summary>
        public string Title => "辅助资料";

        /// <summary> 本地存储的明细 </summary>
        /// <remarks>如果基础资每次都从数据库查询, 这个没用, 保持null</remarks>
        public List<JSubMessage> Items => null;


        /// <summary> 是否每次从数据库查询 </summary>
        public bool QueryFromDataBase => true;


        /// <summary> 存储在快速查询窗体中,显示的属性,及属性的显示, 这个暂时不用,以后删除 </summary>
        public Dictionary<string, string> DisplayColumns => null;


        /// <summary> 显示的列, 静态 </summary>
        private static readonly string[] _columns = new string[] { nameof(JSubMessage.Code), nameof(JSubMessage.Name) };


        /// <summary> 存储在快速查询窗体中,显示的属性 </summary>
        public string[] Columns => _columns;


        /// <summary> 实体模型的代码属性名称 </summary>
        public string CodeField => nameof(JSubMessage.Code);



        /// <summary> 代码中级别的分隔符 </summary>
        public override string Separator => ".";



        /// <summary> 查询树形图的所有节点 </summary>
        public override IEnumerable<IFastTree> QueryTreeList()
        {
            var rst = DB.FSql.Select<JSubMessage>().Where(a => a.IsDetails == false && a.Isdel == false);

            return rst.ToList().ToList<IFastTree>();
        }


        /// <summary> 查询方法 </summary>
        public List<JSubMessage> Query(string findText, string prefixCode = null)
        {
            var list = DB.FSql.Select<JSubMessage>()
              .Where(a => a.Isdel == false && a.IsDetails == true
                  && (a.Name.Contains(findText) || a.Code.Contains(findText)));

            if (string.IsNullOrEmpty(prefixCode) == false)
            {
                if (prefixCode.EndsWith(".") == false)
                    prefixCode += ".";

                list = list.Where(a => a.Code.StartsWith(prefixCode));
            }

            return list.ToList().OrderBy(a => a.Code).ToList();
        }


        /// <summary> 查询树形图的一个节点下的所有内容 </summary>
        public List<JSubMessage> QueryByGroup(string group)
        {

            return DB.FSql.Select<JSubMessage>()
                .Where(w => w.IsDetails == true && w.Isdel == false && w.Code.StartsWith(group + this.Separator))
                .ToList().OrderBy(a => a.Code).ToList();        //排序

        }

        /// <summary> 使用代码查询其中一个类型,包括明细与非明细 </summary>
        public List<JSubMessage> GetPartByCode(string code)
        {
            return DB.FSql.Select<JSubMessage>().Where(w => w.Isdel == false && w.Code.StartsWith(code)).ToList();
        }

        #endregion


        #region 字分类名称

        //public const string CURRENCY = "";
        //public const string  = "";
        

        #endregion


        #region 权限

        /// <summary> 查询导出权限 </summary>
        public override string LookRight => "01.20.1";

        /// <summary> 保存权限 </summary>
        public override string SaveRight => "01.20.2";

        /// <summary> 修改别人单据权限 </summary>
        public string ModifyRight => "01.20.3";

        /// <summary> 删除别人单据权限 </summary>
        public string DeleteRight => "01.20.4";

        /// <summary> 审核,反审核权限 </summary>
        public override string CheckRight => "01.20.5";

        #endregion



        #region 其他


        /// <summary> 使用代码查询一个 </summary>
        public JSubMessage GetByCode(string code)
        {
            return DB.FSql.Select<JSubMessage>()
              .FirstOrDefault(w => w.IsDetails == true && w.Isdel == false && w.Code == code);
        }


        #endregion


        #region 按钮,事件


        public override bool Check(object obj, IUser user, out string err)
        {
            throw new NotImplementedException();
        }

        public override bool UnCheck(object obj, IUser user, out string err)
        {
            throw new NotImplementedException();
        }


        #endregion



    }
}
